<?php
include '../conn.php';
$data = json_decode($HTTP_RAW_POST_DATA);
$sql = "select * from users_info
        where id = $data->userId
        limit 1";
$isUser = $pdo->getOne($sql);
if($isUser) {
    $sql = "select * from users_info
            where nickname = '$data->nickname' and id != $data->userId";
    $req = $pdo->getOne($sql);
    if($req){
        $arr = [
            "code" => 400,
            "desc" => "此昵称已存在"
        ];
    }else{
        if(!isset($data->avatar)) {
            $sql = "update users_info set
                    nickname = '$data->nickname'
                    where id = $data->userId";
            $req = $pdo->query($sql);
            $sql = "select id,nickname,avatar from users_info
                    where id = $data->userId
                    limit 1";
            $res = $pdo->getOne($sql);
            $arr = [
                "code" => 200,
                "desc" => "修改成功",
                "userInfo" => [
                    "id" => $res['id'],
                    "nickname" => $res['nickname'],
                    "avatar" => "$url$res[avatar]"
                ]
            ];
        }else{
            $avatar = "";
            foreach($data->avatar as $img):
                if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $img, $result)){
                    $type = $result[2];
                    $image_name=date('His').str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT).".".$type;
                    $new_file = "../images/avatar/$image_name";
                    $img_url = substr($new_file,2);
                    if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $img)))){
                        $avatar = "$img_url";
                    };
                };
            endforeach;
            $sql = "update users_info set
                    nickname = '$data->nickname',
                    avatar = '$avatar'
                    where id = $data->userId";
            $req = $pdo->query($sql);
            $sql = "select id,nickname,avatar from users_info
                    where id = $data->userId
                    limit 1";
            $res = $pdo->getOne($sql);
            $arr = [
                "code" => 200,
                "desc" => "修改成功",
                "userInfo" => [
                    "id" => $res['id'],
                    "nickname" => $res['nickname'],
                    "avatar" => "$url$res[avatar]"
                ]
            ];
        }
    }
}else {
    $arr = [
        "code" => 400,
        "desc" => '用户信息错误,请重试'
    ];
}
echo json_encode($arr);